package com.wj.auth.service.impl;

import com.wj.auth.bean.UserInfo;
import com.wj.auth.common.util.jwt.IJWTInfo;
import com.wj.auth.common.util.jwt.JWTInfo;
import com.wj.auth.exception.auth.UserInvalidException;
import com.wj.auth.service.AuthService;
import com.wj.auth.util.user.JwtAuthenticationRequest;
import com.wj.auth.util.user.JwtTokenUtil;
import com.wj.auth.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(12);

    @Override
    public String login(JwtAuthenticationRequest authenticationRequest) throws Exception {
        UserVO userVO = new UserVO();
        userVO.setId(1l);
        userVO.setUsername("admin");
        userVO.setRealName("王四");
        String password = "123456";
        password = encoder.encode(password);
        userVO.setPassword(password);
        UserInfo info = new UserInfo();
        BeanUtils.copyProperties(userVO, info);
        info.setName(userVO.getRealName());
        if (!StringUtils.isEmpty(info.getId())) {
            return jwtTokenUtil.generateToken(new JWTInfo(info.getUsername(), info.getId() + "", info.getName()));
        }
        throw new UserInvalidException("用户不存在或账户密码错误!");
    }

    @Override
    public IJWTInfo validate(String token) throws Exception {
        IJWTInfo infoFromToken = jwtTokenUtil.getInfoFromToken(token);
        return infoFromToken;
    }

    @Override
    public String refresh(String oldToken) throws Exception {
        return jwtTokenUtil.generateToken(jwtTokenUtil.getInfoFromToken(oldToken));
    }
}
